package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexRelative;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;
import dk.itu.samd.group2.tagapastry.messages.forwardStrategies.SinglecastReturnToParentStrategy;
import dk.itu.samd.group2.tagapastry.util.TitleGenerator;

public class UntagMsg extends IndexMsg {

	public static final short TYPE = 4;
	private static final long serialVersionUID = TYPE;
	private String object = null;
	private String hash;

	/*
	 * @param tag Represents object used to untag
	 * @param sender Sender of this message
	 * @param object Object to untag for example "cnn.com"
	 */
	public UntagMsg(Tag tag, NodeHandle sender, String object) {
		super(tag, sender);
		this.object = object;
		// Why don't we take hash from tag keyword ?
		TitleGenerator tg = new TitleGenerator();
		this.hash = tg.generateTitle(object);
		forwardStrategy = new SinglecastReturnToParentStrategy(hash);		
	}

	public UntagMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		object = buf.readUTF();
		this.hash = buf.readUTF();
		forwardStrategy = new SinglecastReturnToParentStrategy(hash);
	}
	
	public int getSize() {
		return tag.getSize() + object.length() + hash.length();
	}


	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);

		if (index == null) {
			return;
		}

		if (index.bufferOrForward(this)) {
			return;
		}

		index.remove(object, hash);

	}

	@Override
	public short getType() {
		return TYPE;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
		buf.writeUTF(object);
		buf.writeUTF(hash);
	}

	@Override
	public String toString() {
		String str = super.toString();
		str += " object : " + object + ", hash: " + hash + " }";
		return str;
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}

	@Override
	public boolean indexCreator() {
		return false;
	}

	@Override
	public IndexMsg cloneForChild(IndexRelative child) {
		return new UntagMsg(child.getTag(), originalSender, object);
	}

}
